package sort;

import java.util.Arrays;

public class guibing {
    public static void main(String[] args) {
        int[] nums={10,6,7,1,1,2,2,2};
        mergesort(nums);
        System.out.println(Arrays.toString(nums));
    }

    private static void mergesort(int[] nums) {
        int left=0;
        int right=nums.length-1;
        mergesortTmp(nums,left,right);
    }

    private static void mergesortTmp(int[] nums, int left, int right) {
        //函数递归出口
        if(left>=right){
            return;
        }
        int mid=(right+left)/2;
        mergesortTmp(nums,left,mid);
        mergesortTmp(nums,mid+1,right);
        //合并
        merge(nums,left,mid,right);
    }

    private static void merge(int[] nums, int left, int mid, int right) {
        int k=0;
        int[] tmp=new int[right-left+1];
        int s1=left;
        int e1=mid;
        int s2=mid+1;
        int e2=right;
        while(s1<=e1&&s2<=e2){
            if(nums[s1]>nums[s2]){
                tmp[k++]=nums[s2++];
            }else{
                tmp[k++]=nums[s1++];
            }
        }
        while(s1<=e1){
            tmp[k++]=nums[s1++];
        }
        while(s2<=e2){
            tmp[k++]=nums[s2++];
        }
        for(int i=0;i<k;i++){
            nums[left+i]=tmp[i];
        }
    }
}
